const fs = require('fs')
const path = require('path')
const proxy = require('./proxy');

async function data() { // 从网站下载数据
    for (let id = 2008; id < 2800; id++) {
        console.log(id);
        const resp = await proxy.GET(`http://www.jiqid.com/mitu/web/listdetail?id=${id}`)
        const json = JSON.parse(resp.body)
        if (json.code) {
            continue;
        }
        const data = JSON.stringify(json, null, 2)
        fs.writeFileSync(`data/${('000' + id).slice(-4)}.json`, data)
    }
}

async function page() { // 从数据中取出链接
    let total = 0
    let page = 1
    let all = true // 写出所有 或 仅未下载的 链接
    if (!fs.existsSync('mp3')) { fs.mkdirSync('mp3') }
    fs.writeFileSync('重命名.sh', '#!/bin/sh\nmkdir -p "国学经典"\nmkdir -p "欢乐儿歌"\nmkdir -p "启蒙英语"\nmkdir -p "童话故事"\n')
    const files = fs.readdirSync('data')
    for (let i = 0; i < files.length; i++) {
        const f = path.join('data', files[i])
        if (!f.endsWith('.json')) {
            continue;
        }
        const json = require(`./${f}`)
        const list = json.body[0].resourceDetail
        for (let j = 0; j < list.length; j++) {
            const d = list[j]
            const p = `mp3/${path.basename(d.auditionURL)}`
            if (all || !fs.existsSync(p)) {
                if (++total % 500 == 0) {
                    ++page
                }
                fs.appendFileSync(`page/${('00' + page).slice(-2)}.txt`, `${d.auditionURL}?_=${d.type}_${d.name}.mp3\r\n`)
            }
            fs.appendFileSync(`重命名.sh`, `cp -f "mp3/${path.basename(d.auditionURL)}" "${d.type}/${name(d)}.mp3" \n`)
        }
    }
}

async function rename() { // 把下载后的文件重命名并归类
    const files = fs.readdirSync('data')
    for (let i = 0; i < files.length; i++) {
        const f = path.join('data', files[i])
        if (!f.endsWith('.json')) {
            continue;
        }
        const json = require(`./${f}`)
        const list = json.body[0].resourceDetail
        for (let j = 0; j < list.length; j++) {
            const d = list[j]
            const src = `mp3/${path.basename(d.auditionURL)}`
            const dst = `${d.type}/` + name(d)
            if (fs.existsSync(src) && !fs.existsSync(dst)) {
                if (!fs.existsSync(d.type)) {
                    fs.mkdirSync(d.type)
                }
                console.log(src, '=>', dst);
                fs.copyFileSync(src, dst);
            }
        }
    }
}

function name(d) {
    return `${d.playlist} ${d.name}.mp3`.replace('/', '_').replace(/"/g, '').replace('?', '？')
}

(async() => {
    // await data()
    // await page()
    await rename()
})()